/**
 * edurender
 * gler_context.c
 * (c) 2009 J. Brad Byrd
 */

#include "gler_context.h"

#include "../er/er_assert.h"
#include "../er/er_memory.h"

#include <edurender/er.h>

#include <limits.h>
#include <windows.h>

static int s_activePfd = 0;

static PIXELFORMATDESCRIPTOR s_pfds[] = 
{
	{
		sizeof(PIXELFORMATDESCRIPTOR),	// size of this pfd
		1,								// version number
		PFD_DRAW_TO_WINDOW |			// support window
		PFD_SUPPORT_OPENGL |			// support OpenGL
		PFD_DOUBLEBUFFER,				// double buffered
		PFD_TYPE_RGBA,					// RGBA type
		24,								// 24-bit color depth
		0, 0, 0, 0, 0, 0,				// color bits ignored
		0,								// no alpha buffer
		0,								// shift bit ignored
		0,								// no accumulation buffer
		0, 0, 0, 0, 					// accum bits ignored
		16,								// 16-bit z-buffer	
		0,								// no stencil buffer
		0,								// no auxiliary buffer
		PFD_MAIN_PLANE,					// main layer
		0,								// reserved
		0, 0, 0							// layer masks ignored
	},
};

//static GLERContext *s_context = 0;

int glerGetPixelFormatCount()
{
	return sizeof(s_pfds) / sizeof(s_pfds[0]);
}

const PIXELFORMATDESCRIPTOR *glerDescribePixelFormat(int index)
{
	ER_ASSERT(index > 0 && index <= glerGetPixelFormatCount());
	
	return &s_pfds[index - 1];
}

void glerSetPixelFormat(int index)
{
	ER_ASSERT(s_activePfd == 0);
	
	s_activePfd = index;
}

GLERContext *glerCreateContext(HDC hdc)
{
	RECT rect;
	HWND window = WindowFromDC((HDC)hdc);
	GLERContext *c;	
	
	ER_ASSERT(hdc != INVALID_HANDLE_VALUE);
	
	if (window == NULL)
		return NULL;
	
	GetClientRect(window, &rect);

	c = (GLERContext *)ER_MALLOC(sizeof(GLERContext));

	if (c == NULL)
		return NULL;
	
	if (erCreateContext(rect.right - rect.left, rect.bottom - rect.top, window, &c->er) != ER_RESULT_OK)
	{
		ER_FREE(c);
		return NULL;
	}
	
	c->hdc = hdc;
	
	c->imm = ER_FALSE;
	memset(c->immVerts, 0, sizeof(c->immVerts));
	c->immIndex = 0;
	
	c->matrixMode = GL_MODELVIEW;
	c->mvIndex = 0;
	c->projIndex = 0;
	erIdentityMatrix(&c->mvStack[0]);
	erIdentityMatrix(&c->projStack[0]);
	
	return c;
}

void glerDestroyContext(GLERContext *context)
{
	ER_ASSERT(context != NULL);
	
	erDestroyContext(context->er);
	ER_FREE(context);
}

/*
BOOL glerMakeCurrent(HDC hdc, GLERContext *context)
{
	if (hdc == NULL && context == NULL)
	{
		s_context = NULL;
		return TRUE;
	}
	
	if (context->hdc != hdc)
		return FALSE;
		
	s_context = context;
	
	return TRUE;
}
*/
/*
BOOL glerSwapBuffers(HDC hdc)
{
	if (s_context->hdc != hdc)
		return FALSE;
	
	//erClearColorBuffer(s_context->er, 0.0f, 1.0f, 0.0f, 1.0f);
	return erSwapBuffers(s_context->er) == ER_RESULT_OK;
}
*/
/*
GLERContext *glerGetCurrentContext()
{
	return s_context;
}
*/